const { $Message } = require('../../dist/base/index');
const auth = require('../../util/auth');
const util = require('../../util/util')
const common = require('../../util/common');
const db = wx.cloud.database();
const app = getApp();
const SUBSCRIPT_ID = 'GANLZOLIBPeVeTJ5walgnLEb-hGzp3zIdhFibBKfZIY'
Page({
  data: {
    loadingHidden: true,
    addText: '',
    focus: false,
    status: '1', 
    isStart: false,
    curLists: [],
    curLists: [],
    contentList: [],
    subscriptData:{},
    contents: '',
    editIndex: 0,
    delBtnWidth: 100, // 删除按钮宽度单位（rpx）
  },

  onLoad: function() {
    // 设置一个时间，来保存当前日期
    var that = this
    // if (wx.getStorageSync('currentDate') == null) {
    //   wx.setStorageSync('currentDate', new Date().toLocaleDateString())
    // }    
    that.setData({      
      isStart: wx.getStorageSync('isStart')
    })
  },

  onShow: function() {
    // 进入页面时，获取缓存的数据,如果缓存数据不存在，则查询数据库
    var that = this
    var custlist = [];
    var currentDate = wx.getStorageSync('currentDate') || util.formatDate(new Date())
    var isStart = wx.getStorageSync('isStart')
    // console.log("currentDate",currentDate)
    // console.log("isStart",isStart);
    // console.log("new Date()",util.formatDate(new Date()));
    // 如果已经开启了任务，但是已过当前日期，则任务重新开始
    if (isStart && (new Date(currentDate).getTime() != new Date(util.formatDate(new Date())).getTime())) {
      console.log("任务已过期：",currentDate)
      that.setData({
        isStart: false
      })      
      wx.removeStorageSync('curLists')
      wx.removeStorageSync('isStart')
    }
    custlist = wx.getStorageSync('curLists');
    if (custlist.length < 1 || custlist == []) {
      that.getTask();
    }
    if (custlist != [] && custlist.length > 0) {
      that.showCur(custlist);
    }
  },

  // 开启任务提醒
  startTask() {
    var that = this
    if (that.data.curLists.length < 1) {
      $Message({
        content: '请添加一条任务',
        type: 'warning',
        duration: 2
      });
      return;
    }
    // 如果获取不到 openid ,则先授权，这里的 app.globalData.openid 可能还获取不到，所以再次读取存储中的openid
    var openid = app.globalData.openid || wx.getStorageSync('openid');
    if ((openid && openid != '')) {
      app.globalData.openid = openid
      // 获取订阅消息授权
      that.getSubscriptAuthorize();
    } else {
      that.getUserProfile()
    }
    
    //that.sendMsg()
  },

  // 添加一条任务
  addOneTask() {
    var that = this
    if (that.data.curLists.length >= 3) {
      wx.showToast({
        title: '最多只能添加三个任务，不要贪多哦!',
        icon: 'none',
        duration: 3000
      });
      return;
    }
    if (!that.data.addText.trim()) {
      return
    }
    var temp = that.data.curLists
    var addT = {
      id: new Date().getTime(),
      content: that.data.addText,
      status: '2'
    }
    temp.push(addT)
    that.showCur(temp)
    wx.setStorage({
      key:"curLists",
      data: that.data.curLists
    })
    
    // 清空输入框
    that.setData({
      addText: ''
    })
  },

  // 获取任务输入框内容
  inputValue: function (e) {
    this.setData({
      addText: e.detail.detail.value
    })
  },

  // 获取全部任务内容
  getAllTask() {
    let curLists = this.data.curLists;
    let contents= ''
    let contentList = []
    for(let i = 0; i < curLists.length; i++) {
      let item = curLists[i]
      contentList.push(item.content)
      contents += item.content + ",\n"
    }
    this.setData({
      contents: contents.substr(0, 20),
      contentList: contentList
    })
  },

  // 时间测试
  gettime() {
    var myDate = new Date();    
    console.log(myDate.toLocaleDateString());     //获取当前日期
    console.log(util.formatDate(myDate));     //获取当前日期
    console.log(myDate.toLocaleTimeString());     //获取当前时间
    console.log(myDate.toLocaleString());        //获取日期与时间
    console.log(db.serverDate())
    console.log(util.formatDateTime(myDate))
    console.log(new Date(util.formatDateTime(myDate)).getTime())
    console.log(new Date(wx.getStorageSync('currentDate')).getTime());
    console.log(app.globalData.openid);
    console.log(wx.getStorageSync('openid'));
    console.log(Date.parse(util.formatDateTime(myDate)));
    console.log(new Date(Date.parse(util.formatDateTime(myDate))));

  },

  // async getdb() {
  //   // 先取出集合记录总数
  //   const countResult = await db.collection('taskmsg').count()
  //   const total = countResult.total
  //   // 计算需分几次取
  //   const batchTimes = Math.ceil(total / 100)
  //   const MAX_LIMIT = 100;
  //   const tasks = []
  //   const _ = db.command
  //   for (let i = 0; i < batchTimes; i++) {
  //     const promise = await db.collection('taskmsg')
  //     .where({
  //       isSend: false
  //     })
  //     .get()
  //     tasks.push(promise)
  //   }
  // },

  // 将任务列表保存到数据库
  savTask: async function() {
    var that = this
    var date = new Date();
    var content = JSON.stringify(that.data.curLists)
    that.setData({
      loadingHidden: false
    })
    // 敏感内容检测
    wx.cloud.callFunction({
      name: 'contentCheck',
      data: {
        msg: content
      },
      success: function(res) {
        db.collection('taskmsg').add({
          // data 字段表示需新增的 JSON 数据
          data: {
            openid: app.globalData.openid,
            templateId: SUBSCRIPT_ID,
            page: 'diary',
            contents: that.data.curLists,
            noticeDate: util.formatDate(date),
            remark: "任务提醒",
            status: that.data.status,
            createDate: new Date(date.toLocaleDateString()),
            createTime: db.serverDate(),
            isSend: false, // 消息发送状态设置为 false
            isStart: true // 任务开启
          }
        })
        .then(res => {
          that.setData({
            isStart: true
          })
          wx.setStorageSync('isStart', true)
          wx.setStorageSync('currentDate', util.formatDate(new Date()))
          wx.setStorage({
            data: true,
            key: 'refreshTaskCount',
          })
        })
      },
      fail: function(err) {
        wx.showToast({
          title: '含敏感内容',
          icon: 'error',
          duration: 1500
        });
      },
      complete: function() {
        that.setData({
          loadingHidden: true
        })
      }
    })
    // var isPassCheck = await common.contentCheck(content)
    // if (isPassCheck) {
    //   db.collection('taskmsg').add({
    //     // data 字段表示需新增的 JSON 数据
    //     data: {
    //       openid: app.globalData.openid,
    //       templateId: SUBSCRIPT_ID,
    //       page: 'diary',
    //       contents: that.data.curLists,
    //       noticeDate: util.formatDate(date),
    //       remark: "任务提醒",
    //       status: that.data.status,
    //       createDate: new Date(date.toLocaleDateString()),
    //       createTime: db.serverDate(),
    //       isSend: false, // 消息发送状态设置为 false
    //       isStart: true // 任务开启
    //     }
    //   })
    //   .then(res => {
    //     that.setData({
    //       isStart: true
    //     })
    //     wx.setStorageSync('isStart', true)
    //     wx.setStorageSync('currentDate', util.formatDate(new Date()))
    //     wx.setStorage({
    //       data: true,
    //       key: 'refreshTaskCount',
    //     })
    //   })
    // } else {
    //   wx.showToast({
    //     title: '含敏感内容',
    //     icon: 'error',
    //     duration: 1500
    //   });
    // }        
  },

  // 获取当日任务
  getTask() {
    console.log("getTask 查询");
    var that = this
    var date = new Date();
    const _ = db.command
    let curLists = []
    db.collection('taskmsg').where({
      // data 字段表示需新增的 JSON 数据
      createDate: _.eq(new Date(date.toLocaleDateString()))
    }).get()
    .then(res => {
      var result = res.data
      if (result != [] && result.length > 0) {
        curLists = result[0].contents
        this.setData({
          curLists,
          isStart: result[0].isStart
        })
        wx.setStorageSync('curLists', curLists)
        wx.setStorageSync('isStart', result[0].isStart)
      }
    })
  },

  // 显示任务列表
  showCur: function (data) {
    if (this.data.status === '1') {
      this.setData({
        curLists: data,
        curLists: data
      })
    } else {
      this.setData({
        curLists: data,
        curLists: data.filter(item => +item.status === (this.data.status - 2))
      })
    }
  },

  // 删除任务
  delTodo: function (e) {
    var that = this
    var item = e.currentTarget.dataset.item
    var temp = that.data.curLists
    temp.forEach( (el, index) => {
      if (el.id === item) {
        temp[index].txtStyle = 'left:0'
        wx.showModal({
          title: '',
          content: '您确定要删除吗？',
          confirmText: "确定",
          cancelText: "考虑一下",
          success: function (res) {
            if (res.confirm) {
                temp.splice(index, 1)
                that.showCur(temp)
                wx.setStorage({
                  key:"curLists",
                  data: temp
                })
            } else {
                that.showCur(temp)
              }
          }
        })
      }
    })
    
  },

  touchS: function (e) {
    // console.log('开始：' + JSON.stringify(e))
    // 是否只有一个触摸点
    if(e.touches.length === 1){
      this.setData({
        // 触摸起始的X坐标
        startX: e.touches[0].clientX
      })
    }
  },
  touchM: function (e) {
    // console.log('移动：' + JSON.stringify(e))
    var that = this
    if(e.touches.length === 1){
     // 触摸点的X坐标
      var moveX = e.touches[0].clientX
      // 计算手指起始点的X坐标与当前触摸点的X坐标的差值
      var disX = that.data.startX - moveX
     // delBtnWidth 为右侧按钮区域的宽度
      var delBtnWidth = that.data.delBtnWidth
      var txtStyle = ''
      if (disX == 0 || disX < 0){ // 如果移动距离小于等于0，文本层位置不变
        txtStyle = 'left:0'
      } else if (disX > 0 ){ // 移动距离大于0，文本层left值等于手指移动距离
        txtStyle = 'left:-' + disX + 'rpx'
        if(disX >= delBtnWidth){
          // 控制手指移动距离最大值为删除按钮的宽度
          txtStyle = 'left:-' + delBtnWidth + 'rpx'
        }
      }
      // 获取手指触摸的是哪一个item
      var index = e.currentTarget.dataset.index;
      var list = that.data.curLists
      // 将拼接好的样式设置到当前item中
      list[index].txtStyle = txtStyle
      // 更新列表的状态
      this.setData({
        curLists: list
      });
    }
  },
  touchE: function (e) {
    // console.log('停止：' + JSON.stringify(e))
    var that = this
    if(e.changedTouches.length === 1){
      // 手指移动结束后触摸点位置的X坐标
      var endX = e.changedTouches[0].clientX
      // 触摸开始与结束，手指移动的距离
      var disX = that.data.startX - endX
      var delBtnWidth = that.data.delBtnWidth
      // 如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth/2 ? 'left:-' + delBtnWidth + 'rpx' : 'left:0'
      // 获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index
      var list = that.data.curLists
      list[index].txtStyle = txtStyle
      // 更新列表的状态
      that.setData({
        curLists: list
      });
    }
  },

  getOpenId: function() {
    wx.cloud.callFunction({
      name: 'getopenId'
    }).then(res => {
      console.log(res)
    }) 
  },

  // 获取授权
  getSubscriptAuthorize: function() {
    var that = this
    wx.requestSubscribeMessage({
      tmplIds: [SUBSCRIPT_ID],
      success(res) {
        if (res[SUBSCRIPT_ID] === 'accept') {
          that.getAllTask()
          console.log("授权成功", res)
          // 授权成功后再将任务添加到数据库
          that.savTask()
        }                
      },
      fail(res) {
        console.log("授权失败", res)
        return false
      }
    })
  },

  sendMsg: function() {
    var that = this
    wx.cloud.callFunction({
      name: 'sendSubscriptMsg',
      data: {
        templateId: SUBSCRIPT_ID,
        data: that.data.subscriptData,
        page: 'diary'
      }
    }).then(res => {
      console.log("发送订阅消息成功", res)
    }).catch(res => {
      console.log("发送订阅消息失败", res)
    })
  },

  //-----开启任务之前需要获得授权点击授权--------------------------
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '存储用户日记数据', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)//userInfo登录人微信信息
        auth.saveAuthLocalUserInfo(res.userInfo)
        app.globalData.userInfo = res.userInfo;//存全局的用户信息
        auth.getOpenId();      
      }
    })    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的任务',
      path: '/page/diary/index'
    }
  },
  
  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '水滴石记',
      path: '/page/diary/index'
    }
  },
})
